package com.lin.consumer;

import com.lin.util.RabbitUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;

import java.nio.charset.StandardCharsets;

@Controller
public class Demo5Consumer {
    private static String EXCHANGE_NAME;

    @Value("${queue.demo5_exchange_name}")
    public void  setQueueName(String exchangeName) {
        EXCHANGE_NAME = exchangeName;
    }

    public static void work(String topic) throws Exception {
        Connection connection = RabbitUtil.getConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME,"topic");
        String queueName = channel.queueDeclare().getQueue();
//        绑定对应的主题key
        channel.queueBind(queueName,EXCHANGE_NAME,topic);
        System.out.println("topic worker: "+ topic + " is start listen");
        DeliverCallback deliverCallback = (consumerTag,delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println("topic worker: "+ topic + " receive message: " + message);
        };
        channel.basicConsume(queueName,true,deliverCallback,consumerTag->{});
    }
}
